package com.yq.cp.utils.wechat.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;


public class DecryptUtil {

    /**
     * 解密微信小程序加密数据
     *
     * @param data       加密数据
     * @param sessionKey sessionKey
     * @param iv         iv
     * @return 明文
     */
    public static String decrypt(String data, String sessionKey, String iv) {
        try {
            byte[] deData = Base64.getDecoder().decode(data);
            byte[] deIv = Base64.getDecoder().decode(iv);
            byte[] deKey = Base64.getDecoder().decode(sessionKey);
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(deIv);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(deKey, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] bytes = cipher.doFinal(deData);
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
